import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
import { RootState } from '../../app/store'
import { login } from './userAPI'

interface UserState {
  loading: boolean
  error: string | null
  token: string | null
}

const initialState: UserState = {
  loading: false,
  error: null,
  token: localStorage.getItem('token') || null,
}

export const _sendMessageToChromeExtension = (message: Object) => {
  // The ID of the extension we want to talk to.
  const extensionId = 'jacjcdnicdfgdgdfoohhfimgfpbhfpop'
  chrome.runtime.sendMessage(extensionId, message, function (response) {
    if (!response.success) {
      console.log('hasError')
    }
  })
}

export const signIn = createAsyncThunk(
  'user/login',
  async (parameters: UserInfo) => {
    const { data } = await login(parameters)
    return data.data?.access_token
  },
)

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    logOut: state => {
      state.token = null
      state.error = null
      state.loading = false
      localStorage.removeItem('token')
      _sendMessageToChromeExtension({ isLoginOut: true })
      window.location.reload()
    },
  },
  extraReducers: {
    [signIn.pending.type]: state => {
      state.loading = true
    },
    [signIn.fulfilled.type]: (state, action) => {
      let token = action.payload
      state.token = token
      state.loading = false
      state.error = null
      localStorage.setItem('token', token)
      _sendMessageToChromeExtension({ token })
    },
    [signIn.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.loading = false
      state.error = action.payload
    },
  },
})

export const { logOut } = userSlice.actions

export const getToken = (state: RootState) => state.user?.token

export default userSlice.reducer
